import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/index.vue'
import { useAuthStore } from '@/store/modules/auth'
import { useMenuStore } from '@/store/modules/menu'

// 所有路由
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { title: '登录/注册', hidden: true }
  },
  {
    path: '/',
    redirect: '/dashboard'
  },
  // Dashboard 设为公共可访问
  {
    path: '/dashboard',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Dashboard.vue'),
        meta: { title: '首页', icon: 'house' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { hidden: true }
  }
]

// 项目路由
const projectRoutes: RouteRecordRaw[] = [
  {
    path: '/project',
    component: Layout,
    redirect: '/project/list',
    meta: { title: '项目管理', icon: 'document' },
    children: [
      {
        path: 'list',
        name: 'ProjectList',
        component: () => import('@/views/project/List.vue'),
        meta: { title: '项目列表', icon: 'list' }
      },
      {
        path: 'create',
        name: 'ProjectCreate',
        component: () => import('@/views/project/Create.vue'),
        meta: { title: '创建项目', hidden: true }
      },
      {
        path: 'edit/:id',
        name: 'ProjectEdit',
        component: () => import('@/views/project/Edit.vue'),
        meta: { title: '编辑项目', hidden: true }
      },
      {
        path: 'detail/:id',
        name: 'ProjectDetail',
        component: () => import('@/views/project/Detail.vue'),
        meta: { title: '项目详情', hidden: true }
      },
      {
        path: 'config/:id',
        name: 'ProjectConfig',
        component: () => import('@/views/project/Config.vue'),
        meta: { title: '项目配置', hidden: true }
      }
    ]
  },
  {
    path: '/deploy',
    component: Layout,
    redirect: '/deploy/list',
    meta: { title: '部署管理', icon: 'upload' },
    children: [
      {
        path: 'list',
        name: 'DeployList',
        component: () => import('@/views/deploy/List.vue'),
        meta: { title: '部署列表', icon: 'list' }
      },
      {
        path: 'create',
        name: 'DeployCreate',
        component: () => import('@/views/deploy/Create.vue'),
        meta: { title: '创建部署', icon: 'plus', hidden: true }
      },
      {
        path: 'detail/:id',
        name: 'DeployDetail',
        component: () => import('@/views/deploy/Detail.vue'),
        meta: { title: '部署详情', hidden: true }
      },
      {
        path: 'local',
        name: 'LocalDeploy',
        component: () => import('@/views/deploy/LocalDeploy.vue'),
        meta: { title: '本地文件部署', icon: 'upload' }
      }
    ]
  },
  {
    path: '/server',
    component: Layout,
    redirect: '/server/list',
    meta: { title: '服务器管理', icon: 'cpu' },
    children: [
      {
        path: 'list',
        name: 'ServerList',
        component: () => import('@/views/server/List.vue'),
        meta: { title: '服务器列表', icon: 'list' }
      },
      {
        path: 'create',
        name: 'ServerCreate',
        component: () => import('@/views/server/Create.vue'),
        meta: { title: '添加服务器', hidden: true }
      },
      {
        path: 'edit/:id',
        name: 'ServerEdit',
        component: () => import('@/views/server/Edit.vue'),
        meta: { title: '编辑服务器', hidden: true }
      },
      {
        path: 'detail/:id',
        name: 'ServerDetail',
        component: () => import('@/views/server/Detail.vue'),
        meta: { title: '服务器详情', hidden: true }
      }
    ]
  },
  {
    path: '/system',
    component: Layout,
    redirect: '/system/users',
    meta: { title: '系统管理', icon: 'setting' },
    children: [
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('@/views/user/List.vue'),
        meta: { title: '用户管理', icon: 'user' }
      },
      {
        path: 'roles',
        name: 'RoleManagement',
        component: () => import('@/views/role/List.vue'),
        meta: { title: '角色管理', icon: 'user' }
      },
      {
        path: 'permissions',
        name: 'PermissionManagement',
        component: () => import('@/views/system/permission/List.vue'),
        meta: { title: '权限管理', icon: 'lock' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { hidden: true }
  }
];

// 合并所有路由
routes.push(...projectRoutes);

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore();
  
  // 检查localStorage中的token，确保与store同步
  const localToken = localStorage.getItem('access_token') || localStorage.getItem('token');
  if (localToken && !authStore.token) {
    authStore.setToken(localToken);
  }
  
  // 获取token
  const hasToken = authStore.token;
  
  if (hasToken) {
    if (to.path === '/login') {
      // 已登录，重定向到首页
      next({ path: '/' });
    } else {
      // 检查是否需要加载菜单权限
      const menuStore = useMenuStore();
      
      if (menuStore.routes.length === 0) {
        // 如果菜单路由为空，尝试获取菜单权限
        try {
          // 获取菜单权限
          await authStore.getMenuPermissions();
        } catch (error) {
          console.error('加载菜单权限出错:', error);
          // 即使出错也继续导航，但可能会导致权限问题
        }
      }
      
      // 继续导航
      next();
    }
  } else {
    // 未登录：放行公共页面
    const publicPaths = ['/login'];
    if (publicPaths.includes(to.path)) {
      next();
    } else {
      // 重定向到登录页
      console.log('未登录，重定向到登录页, 当前路径:', to.path);
      next(`/login?redirect=${to.path}`);
    }
  }
})

export default router
